<template>
  <div class="step-box">
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <div class="form-box">
        <p class="sub-title">门店基础信息</p>
        <div class="form-item">
          <div class="form-flex-item">
            <el-form-item label="" prop="shopType">
              <el-radio-group v-model="shopType" clearable @input="changeShopType">
                <el-radio :label="1">经营单个门店</el-radio>
                <el-radio :label="2">经营多个门店</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div v-if="shopType === 2" class="tabs-box">
            <el-tabs v-model="shopIndex" type="card" editable @tab-click="selectTab" @edit="handleTabsEdit">
              <el-tab-pane
                v-for="(item, index) in shopList"
                :key="index"
                :label="`门店${index + 1}`"
                :name="index.toString()"
              />
            </el-tabs>
          </div>

          <div class="form-flex-item">
            <el-form-item label="业态：" prop="businessType">
              <el-cascader
                v-model="form.businessType"
                :options="categoryList"
                :show-all-levels="false"
                :props="{label: 'name', value: 'id', children: 'categoryTreeVOS', multiple: true, emitPath: false}"
                clearable
              />
            </el-form-item>
          </div>
          <div class="form-flex-item">
            <el-form-item label="门店名称：" prop="scenicName">
              <el-input v-model="form.scenicName" placeholder="请输入" clearable />
            </el-form-item>
          </div>
          <div class="form-flex-item">
            <el-form-item label="所在区域：" prop="scenicAddress">
              <el-cascader
                v-model="form.scenicAddress"
                :options="areaList"
                clearable
              />
            </el-form-item>
          </div>
          <div class="form-flex-item">
            <el-form-item label="门店地址：" prop="scenicDetailAddress">
              <el-autocomplete
                v-model.trim="form.scenicDetailAddress"
                clearable
                placeholder="请输入"
                :trigger-on-focus="false"
                :fetch-suggestions="getMapSuggestList"
                @select="selectAddress"
                @clear="clearAddress"
              />
            </el-form-item>
          </div>
          <div class="form-flex-item">
            <el-form-item>
              <div id="mapContainer" class="map-box" />
            </el-form-item>
          </div>
          <div class="form-flex-item">
            <el-form-item label="门店坐标：" prop="coordinate">
              <el-input v-model="form.coordinate" placeholder="根据详细地址自动获取坐标" disabled />
            </el-form-item>
          </div>
          <div class="form-flex-item">
            <el-form-item label="门店联系电话：" prop="phones">
              <p v-for="(item,index) in form.phoneNumbers" :key="index" class="phone-item">
                <el-input v-model="item.phone" placeholder="请输入" clearable />
                <el-button v-if="index === 0" class="handle-phone" type="primary" @click="addPhoneHandle">增加</el-button>
                <el-button v-else class="handle-phone" @click="deletePhoneHandle(index)">删除</el-button>
              </p>
            </el-form-item>
          </div>
          <div class="form-flex-item">
            <el-form-item label="门店图片：" prop="scenicImgs">
              <UploadFile :file-list="form.scenicImgs" :limit="10" @change="uploadHandle">
                <div slot="tip">
                  <p>JPG、JPEG、PNG单张图片大小不超过10M，至少上传1张，最多上传10张</p>
                </div>
              </UploadFile>
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>

import { getCategoryList } from '@/api/common'
import UploadFile from '@/components/UploadFile/index.vue'
import { mapKey } from '@/utils/const'
import { AREA_LIST } from '@/utils/enum'
export default {
  name: 'Step4',
  components: {
    UploadFile
  },
  props: {
    industryCode: {
      type: String,
      default: ''
    },
    id: {
      type: [String, Number],
      default: ''
    },
    formDetail: {
      type: Array,
      default: () => []
    }
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      const phones = []
      this.form.phoneNumbers.map(item => {
        if (item.phone) {
          phones.push(item.phone)
        }
      })
      if (phones.length) {
        callback()
      } else {
        callback(new Error('请输入门店联系电话'))
      }
    }
    return {
      map: '', // 地图实例
      areaList: AREA_LIST,
      categoryList: [],
      form: {},
      shopIndex: '0',
      shopType: 1,
      shopItem: {
        businessType: [],
        scenicName: '',
        scenicAddress: [],
        scenicDetailAddress: '',
        coordinate: '',
        phoneNumbers: [{
          phone: ''
        }],
        scenicImgs: ''
      },
      shopList: [],
      rules: {
        businessType: [
          { required: true, message: '请选择业态', trigger: ['change'] }
        ],
        scenicName: [
          { required: true, message: '请输入门店名称', trigger: ['blur'] }
        ],
        scenicAddress: [
          { required: true, message: '请选择所在区域', trigger: ['change'] }
        ],
        scenicDetailAddress: [
          { required: true, message: '请输入门店地址', trigger: ['blur'] }
        ],
        coordinate: [
          { required: true, message: '请搜索门店地址', trigger: ['blur'] }
        ],
        phones: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        scenicImgs: [
          { required: true, message: '请上传门店图片', trigger: ['change'] }
        ]
      }
    }
  },

  created() {
    if (this.id && this.formDetail.length) {
      this.shopList = this.formDetail
      this.shopType = this.formDetail.length === 1 ? 1 : 2
    } else {
      this.shopList.push({
        ...this.shopItem,
        phoneNumbers: [{
          phone: ''
        }]
      })
    }
    this.form = this.shopList[0]
    this.getCategoryList()
    this.loadScript()
  },

  methods: {

    // 获取类目
    getCategoryList() {
      const data = {
        industryCode: this.industryCode
      }
      getCategoryList(data).then(res => {
        this.categoryList = res || []
      }).catch(() => {})
    },

    // 切换门店类型
    changeShopType(value) {
    },

    // 编辑tabs
    handleTabsEdit(targetName, action) {
      targetName = Number(targetName)
      if (action === 'add') {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.shopList.push({
              ...this.shopItem,
              phoneNumbers: [{
                phone: ''
              }]
            })
            this.shopIndex = (this.shopList.length - 1).toString()
            this.form = this.shopList[this.shopIndex]
            this.initMap()
          } else {
            return false
          }
        })
      }
      if (action === 'remove') {
        if (this.shopList.length === 1) {
          return false
        }
        this.shopIndex = '0'
        this.shopList = this.shopList.filter((item, index) => index !== targetName)
        this.form = this.shopList[0]
      }
    },

    // 选择tab
    selectTab(tab) {
      this.shopIndex = tab.index
      this.form = this.shopList[this.shopIndex]
      this.initMap()
      this.$refs.form.clearValidate()
    },

    loadScript() {
      window.initMap = () => {
        this.initMap()
      }
      const script = document.createElement('script')
      script.src = `https://api.map.baidu.com/api?v=3.0&ak=${mapKey}&callback=initMap`
      document.head.appendChild(script)
    },

    // 初始化地图
    initMap() {
      const { lon, lat } = this.form
      // eslint-disable-next-line no-undef
      this.map = new BMap.Map('mapContainer') // 创建Map实例
      // eslint-disable-next-line no-undef
      this.map.centerAndZoom(new BMap.Point(lon || 120.08158189136478, lat || 29.311150347824732), 15) // 初始化地图,设置中心点坐标和地图级别

      if (lon && lat) {
        // eslint-disable-next-line no-undef
        const point = new BMap.Point(lon, lat)
        this.addMarker(point)
      }
    },

    // 添加覆盖物
    addMarker(point) {
      this.map.centerAndZoom(point, 15)
      // eslint-disable-next-line no-undef
      const marker = new BMap.Marker(point) // 创建标注
      this.map.addOverlay(marker)
      this.form.coordinate = `${point.lng},${point.lat}`
    },

    // 获取输入建议
    getMapSuggestList(keyword, cb) {
      if (keyword) {
        const options = {
          onSearchComplete: function(results) {
            // eslint-disable-next-line no-undef
            if (local.getStatus() === BMAP_STATUS_SUCCESS) {
              // 判断状态是否正确
              const suggestList = []
              for (let i = 0; i < results.getCurrentNumPois(); i++) {
                const temp = {
                  value: results.getPoi(i).title,
                  point: results.getPoi(i).point
                }
                suggestList.push(temp)
              }
              cb(suggestList)
            } else {
              cb()
            }
          }
        }
        // eslint-disable-next-line no-undef
        const local = new BMap.LocalSearch(this.map, options)
        local.search(keyword)
      }
    },

    // 选中地址
    selectAddress(item) {
      const point = item.point
      this.addMarker(point)
    },

    // 清除地址
    clearAddress() {
      this.initMap()
      this.form.coordinate = ''
    },

    // 增加电话
    addPhoneHandle() {
      this.form.phoneNumbers.push({
        phone: ''
      })
    },

    // 删除电话
    deletePhoneHandle(index) {
      this.form.phoneNumbers.splice(index, 1)
    },

    uploadHandle(payload) {
      const fileList = payload.fileList
      const result = []
      fileList.map(item => {
        result.push(item.url)
      })
      this.form.scenicImgs = result.join(',')
      this.$refs.form.validateField('scenicImgs')
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/components/Approve/step.scss';
::v-deep{
  .BMap_cpyCtrl, .anchorBL{
    display: none;
  }
}
.tabs-box{
  padding: 0 50px 0 100px;
  display: flex;
  .el-tabs{
    min-width: 200px;
  }
}

.map-box{
  width: 400px;
  height: 300px;
}

.phone-item{
  margin-bottom: 10px;
  .handle-phone{
    margin-left: 20px;
  }
}
</style>
